package com.example.a2032.activity;

import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.a2032.R;
import com.example.a2032.Utils.SharedPreferenceUtils;
import com.example.a2032.Utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.CompositeDisposable;

public class TempMeasureActivity extends BaseActivity {
    private static final String TAG = "TempMeasureActivity";
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_meausre_ready)
    ImageView ivMeausreReady;
    @BindView(R.id.tv_measure_tips1)
    TextView tvMeasureTips1;
    @BindView(R.id.tv_tempValue)
    TextView tvTempValue;
    @BindView(R.id.tvTempUnit)
    TextView tvTempUnit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KeepScreenOn();
        setContentView(R.layout.activity_temp_measure);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        int  tempUnit = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_TempUnit,
                SharedPreferenceUtils.tempUnitC);//默认摄氏度
        tvTempUnit.setText(Utils.getShowTempUnit());
        subscribe(this);
        startTempMeasureTimer();
    }

    CompositeDisposable compositeDisposable = new CompositeDisposable();

    private void startTempMeasureTimer() {
        Utils.startTempMeasureTimer(compositeDisposable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.dispose();
        KeepScreenOff();
    }

    @Override
    public void TempData(float tempData) {
        super.TempData(tempData);
        boolean isVaildData = isVaildData(tempData);
        if (isVaildData) {
            showTempIcon(tempData);
        } else {
            tvMeasureTips1.setText(getString(R.string.measureing));
            tvTempValue.setText("--");
            Glide.with(this).asGif().load(R.drawable.temp_measuring).into(ivMeausreReady);
        }

    }

    void showTempIcon(float tempData) {
        tvMeasureTips1.setText(tempData > 37.2 ? getString(R.string.tempHigh) : getString(R.string.temp_Normal));
        tvTempValue.setText(Utils.getShowTemp(tempData));
        ivMeausreReady.setImageResource(tempData > 37.2 ? R.drawable.temp_result_error : R.drawable.temp_result_normal);
    }

    float lastTemp = 0;

    boolean isVaildData(float tempData) {
        boolean isVaildData = false;
        if (lastTemp != 0) {
            float offset = tempData - lastTemp;
            Log.i(TAG, "isVaildData: " + tempData + " " + lastTemp);
            isVaildData = Math.abs(offset) < 0.5f;
        }
        lastTemp = tempData;
        return isVaildData;
    }
}